<template>
  <el-dialog
    v-loading.lock="loading"
    class="base-dialog"
    :custom-class="'panna-dialog_big'"
    :title="dataList.AddDevice"
    align="center"
    destroy-on-close
    :visible.sync="innerDialogFormVisible"
    @closed="closeDialog"
  >
    <el-form
      ref="formData"
      class="base-pipeline-layout"
      label-width="150px"
      :model="formData"
      :rules="formRules"
      status-icon
    >
      <el-form-item :label="dataList.DeviceClassifyId" prop="classifyId">
        <DeviceCategory v-model="formData.classifyId" :is-all="false" />
      </el-form-item>
      <el-form-item
        :label="dataList.DeviceNumber"
        :label-width="formLabelWidth"
        prop="num"
      >
        <el-input v-model="formData.num" autocomplete="off"></el-input>
      </el-form-item>
      <el-form-item
        :label="
          $i18n.locale === 'en' ? dataList.DeviceEName : dataList.DeviceName
        "
        :label-width="formLabelWidth"
        prop="name"
      >
        <el-input v-model="formData.name" autocomplete="off"></el-input>
      </el-form-item>
      <el-form-item
        :label="dataList.DeviceEName"
        :label-width="formLabelWidth"
        prop="eName"
      >
        <el-input v-model="formData.eName" autocomplete="off"></el-input>
      </el-form-item>
      <el-form-item
        :label="dataList.DeviceSpecifications"
        :label-width="formLabelWidth"
        prop="specifications"
      >
        <el-input
          v-model="formData.specifications"
          autocomplete="off"
        ></el-input>
      </el-form-item>
      <el-form-item
        :label="dataList.DevicepurposeId"
        :label-width="formLabelWidth"
        prop="purposeId"
      >
        <dic-drop-down-list
          v-model="formData.purposeId"
          dict-code="DevicePurpose"
        ></dic-drop-down-list>
      </el-form-item>

      <el-form-item
        :label="dataList.DevicereceiveStatusId"
        :label-width="formLabelWidth"
        prop="receiveStatusId"
      >
        <dic-drop-down-list
          v-model="formData.receiveStatusId"
          dict-code="deviceReceive"
        ></dic-drop-down-list>
      </el-form-item>
      <el-form-item
        :label="dataList.DeviceSupplierName"
        :label-width="formLabelWidth"
        prop="supplierId"
      >
        <SupplierList v-model="formData.supplierId" />
      </el-form-item>

      <el-form-item
        :label="dataList.DeviceUseDate"
        :label-width="formLabelWidth"
        prop="useDate"
      >
        <el-date-picker
          v-model="formData.useDate"
          type="date"
          :placeholder="dataList.DeviceUseDate"
          value-format="yyyy-MM-dd"
        >
        </el-date-picker>
      </el-form-item>
      <el-form-item
        v-if="devicePlatformShowStatus"
        :label="dataList.Deviceplatform"
        :label-width="formLabelWidth"
        prop="platform"
      >
        <!-- <el-input v-model="formData.platform" autocomplete="off"></el-input> -->
        <!-- <DicDropDownList
          v-model="formData.platform"
          :value-is-id-or-code.sync="valueIsIdOrCode"
          dict-code="DevicePlatform"
        /> -->

        <el-select
          ref="select"
          v-model="formData.platform"
          :placeholder="dataList.Placeholder"
        >
          <el-option
            v-for="item in devicePlatformList"
            :key="valueIsIdOrCode ? item.id : item.value"
            :label="item.name"
            :value="valueIsIdOrCode ? item.id : item.value"
          >
          </el-option>
        </el-select>
      </el-form-item>
      <el-form-item
        :label="dataList.DeviceBrand"
        :label-width="formLabelWidth"
        prop="brand"
      >
        <el-input v-model="formData.brand" autocomplete="off"></el-input>
      </el-form-item>
      <el-form-item
        :label="dataList.eDeviceBrand"
        :label-width="formLabelWidth"
        prop="eBrand"
      >
        <el-input v-model="formData.eBrand" autocomplete="off"></el-input>
      </el-form-item>
      <el-form-item
        :label="dataList.Deviceworth"
        :label-width="formLabelWidth"
        prop="worth"
      >
        <el-input v-model="formData.worth" autocomplete="off"></el-input>
      </el-form-item>
      <el-form-item
        :label="dataList.DeviceFactoryNum"
        :label-width="formLabelWidth"
        prop="factoryNum"
      >
        <el-input v-model="formData.factoryNum" autocomplete="off"></el-input>
      </el-form-item>
      <el-form-item
        :label="
          $i18n.locale === 'en'
            ? dataList.eDeviceStorageAddress
            : dataList.DeviceStorageAddress
        "
        :label-width="formLabelWidth"
        prop="storageAddress"
      >
        <el-input
          v-model="formData.storageAddress"
          autocomplete="off"
        ></el-input>
      </el-form-item>
      <el-form-item
        :label="dataList.eDeviceStorageAddress"
        :label-width="formLabelWidth"
        prop="eStorageAddress"
      >
        <el-input
          v-model="formData.eStorageAddress"
          autocomplete="off"
        ></el-input>
      </el-form-item>

      <!-- <el-form-item
        :label="责任人"
        :label-width="formLabelWidth"
        prop="personResponsibleId"
      >
        <UserDropDownList
          v-model="formData.personResponsibleId"
          @getData="getData"
        />
      </el-form-item> -->
      <el-form-item
        :label="dataList.DevicePersonResponsibleId"
        :label-width="formLabelWidth"
        prop="personResponsibleIds"
      >
        <el-select
          v-model="formData.personResponsibleIds"
          multiple
          :placeholder="dataList.EnterDevicePersonResponsibleId"
          filterable
          remote
          reserve-keyword
          :remote-method="remoteGroup"
          :loading="searchUserLoading"
        >
          <el-option
            v-for="item in userList"
            :key="item.id"
            :label="item.name"
            :value="item.id"
          />
        </el-select>
      </el-form-item>
      <el-form-item
        :label="dataList.Devicedepart"
        :label-width="formLabelWidth"
        prop="departIdArray"
      >
        <DepartList
          v-model="formData.departIdArray"
          :level="level"
        ></DepartList>
      </el-form-item>
      <el-form-item
        :label="dataList.DevicePhone"
        :label-width="formLabelWidth"
        prop="phone"
      >
        <el-input v-model="formData.phone" autocomplete="off"></el-input>
      </el-form-item>
      <el-form-item :label="dataList.Deviceoperator" prop="operator">
        <el-select
          v-model="formData.operator"
          multiple
          :placeholder="dataList.Selectoperator"
          filterable
          remote
          reserve-keyword
          :remote-method="remoteGroup"
          :loading="searchUserLoading"
        >
          <el-option
            v-for="item in userList"
            :key="item.id"
            :label="item.name"
            :value="item.id"
          />
        </el-select>
      </el-form-item>
      <el-form-item
        :label="dataList.Devicesort"
        :label-width="formLabelWidth"
        prop="sort"
      >
        <el-input v-model="formData.sort" autocomplete="off"></el-input>
      </el-form-item>
      <el-form-item
        :label="dataList.Deviceremark"
        prop="remark"
        style="width: 100% !important"
      >
        <el-input
          v-model="formData.remark"
          autocomplete="off"
          type="textarea"
          :rows="4"
          maxlength="500"
          show-word-limit
        ></el-input>
      </el-form-item>
      <el-form-item
        :label="dataList.Devicemeasuring"
        prop="measuring"
        style="width: 100% !important"
      >
        <el-input
          v-model="formData.measuring"
          autocomplete="off"
          type="textarea"
          :rows="4"
          maxlength="500"
          show-word-limit
        ></el-input>
      </el-form-item>
      <el-form-item
        :label="dataList.DevicePerformance"
        prop="performance"
        style="width: 100% !important"
      >
        <el-input
          v-model="formData.performance"
          autocomplete="off"
          type="textarea"
          :rows="4"
          maxlength="500"
          show-word-limit
        ></el-input>
      </el-form-item>
      <el-form-item
        :label="dataList.eDevicePerformance"
        prop="ePerformance"
        style="width: 100% !important"
      >
        <el-input
          v-model="formData.ePerformance"
          autocomplete="off"
          type="textarea"
          :rows="4"
          maxlength="500"
          show-word-limit
        ></el-input>
      </el-form-item>
      <el-form-item
        :label="dataList.DeviceEnvironment"
        prop="environment"
        style="width: 100% !important"
      >
        <el-input
          v-model="formData.environment"
          autocomplete="off"
          type="textarea"
          :rows="4"
          maxlength="500"
          show-word-limit
        ></el-input>
      </el-form-item>
      <!-- <el-form-item v-if="qrcodeHide" :label="小程序码">
        <img :src="formData.qrcode"  />
      </el-form-item> -->
      <el-form-item
        :label="dataList.DeviceImg"
        prop="imgArray"
        style="width: 100% !important"
      >
        <div class="deviceAddDialogImg">
          <BaseMultipleUpload
            key="BaseUpload"
            ref="BaseUpload"
            v-model="formData.imgArray"
            business-type="110"
            :is-public-file="isPublicFile"
            :file-size="5120"
            :limit="3"
            :style-c-s-s="styleCSS"
            :multiple="true"
            :show-file-list="true"
            :list-type="'picture-card'"
            style="
              display: flex;
              align-items: start;
              padding-left: 10px;
              flex-direction: column;
            "
            :tip="dataList.DeviceImgTip()"
            :accept="'.jpeg,.jpg,.png,.gif,.bmp,.tiff'"
          />
        </div>
      </el-form-item>

      <el-form-item
        :label="dataList.DeviceVideo"
        prop="videoArray"
        style="width: 100% !important"
      >
        <div class="deviceAddDialogImg">
          <BaseVideoUpload
            key="BaseUpload"
            ref="BaseUpload"
            v-model="formData.videoArray"
            :is-public-file="isPublicFile"
            :file-size="20"
            :limit="1"
            :style-c-s-s="styleCSS"
            :multiple="true"
            :show-file-list="true"
            :list-type="'picture-card'"
            style="
              display: flex;
              align-items: start;
              padding-left: 10px;
              flex-direction: column;
            "
            :tip="dataList.DeviceVideoTip"
            :accept="'.mp4,.mov'"
          />
        </div>
      </el-form-item>

      <el-form-item
        :label="dataList.DeviceAnnex"
        prop="fileArray"
        style="width: 100% !important"
      >
        <div class="deviceAddDialogFile">
          <BaseUploadFile
            key="BaseUploadFile"
            ref="BaseUploadFile"
            v-model="formData.fileArray"
            :is-public-file="isPublicFile"
            business-type="120"
            :file-size="10240"
            :limit="10"
            :multiple="true"
            style="display: flex; align-items: center; padding-left: 10px"
            :tip-text="
              'File Type：pdf、doc、docx、xls、xlsx、zip、rar、apk；' +
              dataList.DeviceAnnexTip
            "
            :accept="'.pdf,.doc,.docx,.xls,.xlsx,.zip,.rar,.apk'"
          />
        </div>
      </el-form-item>
      <el-form-item
        :label="dataList.DeviceTag"
        prop="checkedRows"
        style="width: 100% !important"
      >
        <div class="deviceAddDialogTag">
          <div
            style="
              display: flex;
              flex-direction: row;
              align-items: center;
              height: 100%;
              padding-left: 10px;
              padding-right: 30px;
            "
          >
            <el-button type="primary" @click="selTag">{{
              btn.SelectTag
            }}</el-button>
          </div>
          <div style="display: flex; flex-direction: row">
            <div
              v-for="item in checkedRows"
              :key="item"
              style="
                margin-left: 10px;
                display: flex;
                flex-direction: column;
                justify-content: center;
              "
            >
              <el-image
                :src="item.url"
                style="width: 70px; height: 70px; border-radius: 50%"
              ></el-image>
              <div>{{ item.name }}</div>
              <div style="margin-top: 10px">
                <el-button type="danger" size="mini" @click="delTag(item)">{{
                  btn.Delete
                }}</el-button>
              </div>
            </div>
          </div>
        </div>
      </el-form-item>
    </el-form>
    <div slot="footer" class="dialog-footer" align="center">
      <el-button type="primary" @click="onSubmit">{{ btn.Save }}</el-button>
      <el-button @click="closeDialog">{{ btn.Cancel }}</el-button>
    </div>
    <DeviceTagDialogList
      v-if="deviceTagListDialogVisable"
      ref="deviceTagListDialog"
      :device-tag-list-dialog-visable.sync="deviceTagListDialogVisable"
      :checked-rows.sync="checkedRows"
      @checkedRowsFun="checkedRowsFun"
    ></DeviceTagDialogList>
  </el-dialog>
</template>
<script>
import { getUserListNoPage } from "../../api/PermissionUser.js";
// import UserDropDownList from "../../components/UserDropDownList.vue";
import DeviceCategory from "../../components/DeviceCategory.vue";
import DepartList from "../../components/DepartList.vue";
import DicDropDownList from "../../components/DicDropDownList.vue";
import SupplierList from "../../components/SupplierList.vue";
import DeviceTagDialogList from "../../components/DeviceTagDialogList.vue";
import {getList} from "@/ModuleSysBusiness/api/SysBusiness/SysBusinessCategory.js";
import { purposeId, receiveStatusId } from "../../utils/const";
import { create, getDeviceNum, getDepartIdList } from "../../api/Device";
import { getConfigByKey, getFirstSubConfigByKey } from "../../api/SystemDict";
import { mapGetters } from "vuex";
import { normal } from "../../utils/const";

export default {
  name: "DeviceAddDialog",
  components: {
    // UserDropDownList,
    DepartList,
    DicDropDownList,
    SupplierList,
    DeviceTagDialogList,
    DeviceCategory,
  },
  props: {
    dialogFormVisible: {
      type: Boolean, // 布尔
      default: false, // 必填
    },
    deptreeLevel: {
      type: Boolean, // 布尔
      default: false, // 必填
    },
  },
  data() {
    return {
      getDevicePlatformUrl:
        window.EnvConfig.VUE_APP_BASE_API + "/api/v1/SystemDict/GetListNoPage",
      oldNum: "",
      devicePlatformShowStatus: true,
      innerDialogFormVisible: false,
      deviceTagListDialogVisable: false,
      styleCSS: "text-align:left",
      classifyList: [],
      formLabelWidth: "150px",
      checkedRows: [],
      userList: [],
      valueIsIdOrCode: true,
      devicePlatformList: [],
      searchUserLoading: false,
      isPublicFile: false,
      qrcodeHide: false,
      formData: {
        classifyId: "",
        num: "",
        name: "",
        eName: "",
        specifications: "",
        user: {},
        purposeId: purposeId,
        receiveStatusId: receiveStatusId,
        // personResponsibleId: "",
        storageAddress: "",
        eStorageAddress: "",
        useDate: null,
        factoryNum: "",
        supplierId: "",
        departId: "",
        departIdArray: [],
        remark: "",
        phone: "",
        measuring: "",
        performance: "",
        ePerformance: "",
        environment: "",
        originalVideoName: "",
        storageVideoName: "",
        videoPath: "",
        fileArray: [],
        imgArray: [],
        videoArray: [],
        sysBusinessFileWarehouseList: [],
        sysBusinessImgWarehouseList: [],
        deviceTagInfoList: [],
        statusId: normal,
        platform: "",
        brand: "",
        eBrand: "",
        worth: "",
        operator: [],
        sort: 0,
        qrCode: "",
        personResponsibleIds: [],
        level: -1,
      },
      level: -1,
      formRules: {
        classifyId: [
          {
            required: true,
            trigger: "blur",
            validator: this.Helper.validateFunction,
          },
        ],
        num: [
          {
            required: true,
            trigger: "blur",
            validator: this.Helper.validateFunction,
          },
        ],
        name: [
          {
            required: true,
            trigger: "blur",
            validator: this.Helper.validateFunction,
          },
        ],
        eName: [
          {
            required: true,
            trigger: "blur",
            validator: this.Helper.validateFunction,
          },
        ],
        specifications: [
          {
            required: true,
            trigger: "blur",
            validator: this.Helper.validateFunction,
          },
        ],
        purposeId: [
          {
            required: true,
            trigger: "blur",
            validator: this.Helper.validateFunction,
          },
        ],
        receiveStatusId: [
          {
            required: true,
            trigger: "blur",
            validator: this.Helper.validateFunction,
          },
        ],
        supplierId: [
          {
            required: true,
            trigger: "blur",
            validator: this.Helper.validateFunction,
          },
        ],
        personResponsibleIds: [
          {
            required: true,
            trigger: "blur",
            validator: this.Helper.validateArrayFunction,
          },
        ],
        departIdArray: [
          {
            required: true,
            trigger: "blur",
            validator: this.Helper.validateFunction,
          },
        ],
        phone: [
          {
            required: true,
            trigger: "blur",
            validator: this.Helper.validateFunction,
          },
        ],
      },
      loading: true,
    };
  },
  computed: {
    ...mapGetters(["fileDomain", "fileBucket"]),
    btn() {
      return this.$t("ModuleDevice.buttons");
    },
    dataList() {
      return this.$t("ModuleDevice.Device");
    },
  },

  created() {
    this.loading = false;
    this.innerDialogFormVisible = this.dialogFormVisible;
  },
  mounted() {
    this.initData();
  },
  methods: {
    getData(obj) {
      this.formData.phone = obj.mobile;
      if (obj.departmentIds !== "") {
        var departmentIdlist = obj.departmentIds.split(",");
        getDepartIdList({ departId: departmentIdlist[0] }).then((res) => {
          this.formData.departIdArray = res.data;
        });
      }
    },
    getUser(name = "") {
      return new Promise((resolve) => {
        getUserListNoPage({ name: name }).then((res) => {
          resolve(res.data);
        });
      });
    },
    getFileIsPublic() {
      return new Promise((resolve) => {
        getConfigByKey("DeviceFile", 0).then((res) => {
          resolve(res.data ? res.data[0].value : "0");
        });
      });
    },
    // 搜索人员
    async remoteGroup(query) {
      this.searchUserLoading = true;
      const filter = await this.getUser(query);
      if (filter && filter.length) {
        this.userList = filter;
      }
      this.searchUserLoading = false;
    },
    onSubmit() {
      this.$refs.formData.validate((valid) => {
        if (valid) {
          // 标签
          this.formData.deviceTagInfoList = [];
          this.checkedRows.forEach((item) => {
            var obj = {};
            obj.tagId = item.id;
            this.formData.deviceTagInfoList.push(obj);
          });
          // 视频
          this.formData.videoArray.forEach((item) => {
            this.formData.originalVideoName = item.originalFileName;
            this.formData.storageVideoName = item.storageFileName;
            this.formData.videoPath = item.filePath;
          });

          // 图片
          this.formData.sysBusinessImgWarehouseList = [];
          this.formData.imgArray.forEach((item) => {
            var obj = {};
            obj.fileTpyeCode = 1;
            obj.originalFileName = item.originalFileName;
            obj.storageFileName = item.storageFileName;
            obj.filePath = item.filePath;
            this.formData.sysBusinessImgWarehouseList.push(obj);
          });
          // 附件
          this.formData.sysBusinessFileWarehouseList = [];
          this.formData.fileArray.forEach((item) => {
            var obj = {};
            obj.fileTpyeCode = 2;
            obj.originalFileName = item.name;
            obj.storageFileName = "";
            obj.filePath = item.url2;
            this.formData.sysBusinessFileWarehouseList.push(obj);
          });
          // 部门
          if (this.formData.departIdArray.length > 0) {
            this.formData.departId =
              this.formData.departIdArray[
                this.formData.departIdArray.length - 1
              ];
          } else {
            this.formData.departId = 0;
          }
          if (this.formData.num !== this.oldNum) {
            this.formData.numAuto = 0;
          } else {
            this.formData.numAuto = 1;
          }
          create(this.formData)
            .then((res) => {
              if (this.deptreeLevel) {
                this.openSetting();
              } else {
                this.closeDialog();
              }
            })
            .catch((res) => {});
        } else {
          return false;
        }
      });
    },
    checkedRowsFun(rows) {
      this.checkedRows = [];
      rows.forEach((item) => {
        this.checkedRows.push(item);
        // var flag = false;
        // this.checkedRows.forEach((val) => {
        //   if (val.id === item.id) {
        //     flag = true;
        //   }
        // });
        // if (!flag) {
        //   this.checkedRows.push(item);
        // }
      });
    },
    delTag(obj) {
      this.checkedRows = this.checkedRows.filter((item) => {
        return item.id !== obj.id;
      });
    },
    selTag() {
      this.deviceTagListDialogVisable = true;
    },

    getDevicePlatform() {
      getFirstSubConfigByKey("DevicePlatform").then((res) => {
        if (
          res.data === null ||
          res.data === undefined ||
          res.data.length === 0
        ) {
          this.devicePlatformShowStatus = false;
        } else {
          this.devicePlatformList = res.data;
        }
      });
    },

    async initData() {
      if (this.deptreeLevel) {
        this.level = 2;
      }
      this.getDevicePlatform();

      const userListData = await this.getUser().catch(() => {});
      this.userList = userListData;
     getList({ AppId: 2000, Status: 1 }, { pageIndex: 1, pageSize: 10000 })
        .then((res) => {
          this.classifyList = res.data.dataList;
        });
      getDeviceNum().then((res) => {
        this.formData.num = res.data;
        this.oldNum = res.data;
      });
      const isPublic = await this.getFileIsPublic();
      if (isPublic && isPublic === "1") {
        this.isPublicFile = true;
      }
      this.qrcodeHide = (await this.getQrCode()) === "1";
    },
    getQrCode() {
      return new Promise((resolve) => {
        getConfigByKey("QrCode", 0).then((res) => {
          resolve(res.data ? res.data[0].value : "0");
        });
      });
    },
    closeDialog() {
      this.$emit("update:dialogFormVisible", false);
      this.$emit("getList");
    },
    openSetting() {
      this.$confirm(
        this.$t("ModuleDevice.Message.ToDeviceAppointmentSetting"),
        this.$t("ModuleDevice.buttons.Tips"),
        {
          confirmButtonText: this.$t("ModuleDevice.buttons.Confirm"),
          cancelButtonText: this.$t("ModuleDevice.buttons.Cancel"),
          type: "warning",
        }
      )
        .then(() => {
          this.handleToPage("/AppointmentServiceMangeList");
          // this.$message({
          //   type: "success",
          //   message: "删除成功!",
          // });
        })
        .catch(() => {
          // this.$message({
          //   type: "info",
          //   message: "已取消删除",
          // });
          this.closeDialog();
        });
    },
    handleToPage(path) {
      const { resolved } = this.$router.resolve(path);
      console.log(this.$router.resolve(path));
      if (resolved.path !== path) {
        return this.$message.warning(
          this.$t("ModuleDevice.Message.Unauthorized")
        );
      }
      this.$router.push({
        path: path,
      });
    },
  },
};
</script>
<style scoped lang="scss">
.base-pipeline-layout {
  .el-form-item {
    width: 40% !important;
  }
}
.deviceAddDialogImg {
  border: 1px solid #dcdfe6;
  border-radius: 4px;
  height: 150px;
  ::v-deep .el-upload--picture-card {
    width: 116px;
    height: 88px;
    border: 1px solid #dcdfe6;
  }
  ::v-deep .el-upload-list__item {
    width: 116px;
    height: 88px;
    border: 1px solid #dcdfe6;
  }
  ::v-deep.el-upload {
    display: flex;
    align-items: center;
    justify-content: center;
  }
  ::v-deep .tip-text {
    color: red !important;
    font-size: 12px;
  }
  ::v-deep .el-upload-list--picture-card {
    margin-left: 10px;
  }

  ::v-deep .base-upload {
    display: flex;
    flex-direction: row-reverse;
    margin-top: 10px;
  }
}
.deviceAddDialogFile {
  border: 1px solid #dcdfe6;
  border-radius: 4px;
  height: 150px;
  ::v-deep.base-upload {
    text-align: left;
    display: flex;
    flex-direction: column;
    padding-top: 10px;
    width: 100%;
  }
  ::v-deep .el-upload-list__item {
    width: 50%;
  }
  ::v-deep .el-upload {
    text-align: left;
  }
  ::v-deep .el-upload-list {
    display: flex;
    flex-wrap: wrap;
    justify-content: space-between;
    overflow-y: auto;
  }
  ::v-deep .el-upload__tip {
    color: red;
  }
}
.deviceAddDialogTag {
  border: 1px solid #dcdfe6;
  border-radius: 4px;
  height: 150px;
  display: flex;
  flex-direction: row;
}
</style>
